package com.ykt.service;

import com.ykt.common.utils.LonLatUtil;
import com.ykt.common.utils.UB;
import com.ykt.common.utils.page.PageData;
import com.ykt.common.utils.page.PageParam;
import com.ykt.model.Community;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

/** d
 * @author wing
 * @version 1.0.0
 */
public class CommunityService {

    private final  static Logger LOGGER = LoggerFactory.getLogger(CommunityService.class);

	private Community communityDao = Community.dao;


    public Community find(int communityId){
        return communityDao.findById(communityId);
    }


    public PageData<Community> paginate(PageParam<Map<String, Object>> param){
        Object shopId = param.getP().get("shopId");
        
        List<Community> communities = null;
        if((shopId == null) || !(shopId instanceof Integer)){
        	communities = communityDao.findAll();
        }else {
        	communities = communityDao.findByShopId((int) shopId);
        }
        if(communities == null || communities.isEmpty()){
            return new PageData<>(param.getPageNo(), param.getPageSize(), 0);
        }

        Map<Double, Community> map = new TreeMap<>(new Comparator<Double>() {
            @Override
            public int compare(Double o1, Double o2) {
                return o1 > o2 ? 1:0;
            }
        });

        double lon1 = UB.d(param.getP().get(Community.longitude), 0);
        double lat1 = UB.d(param.getP().get(Community.latitude), 0);

        // 经纬度为0则查询全部在分页
        if(lon1 == lat1 && lon1 == 0){
            return PageData.pageList(communities, param.getPageNo(), param.getPageSize());
        }

        // 经纬度非0则计算全部距离再分页
        for (Community community : communities) {
            double lon2 = UB.d(community.get(Community.longitude), -1);
            double lat2 = UB.d(community.get(Community.latitude), -1);
            if(lon2 == lat2 && lat2 == -1){
                continue;
            }

            double d = LonLatUtil.getDistance(lat1, lon1, lat2, lon2);
            map.put(d, community);
        }

        return PageData.pageList(new ArrayList<>(map.values()), param.getPageNo(), param.getPageSize());
    }



}
